import fs from 'node:fs';

const startMessage = `
\x1b[38;2;255;105;180m
----------------------------------------------------
|   _(＾▽＾)_/ 皮皮突然冲出来吓坏你的崽~    |
----------------------------------------------------
\x1b[0m
`;
logger.info(startMessage);

// 检查是否存在 segment
if (!global.segment) {
  logger.warn(logger.red("哦豁！看起来找不到 segment，小主人要不考虑更新一下Yunzai呢（・∀・）"));
  global.segment = (await import("oicq")).segment;
}

// 读取插件文件夹中的所有插件
const pluginDir = 'plugins/pippi-plugin/apps';
const files = fs.readdirSync(pluginDir).filter(file => file.endsWith('.js'));

let ret = [];
let pluginLogs = []; // 用于记录日志的数组

files.forEach((file) => {
  ret.push(import(`./apps/${file}`).then(
    (module) => {
      const pluginName = file.replace('.js', '');
      pluginLogs.push({
        type: 'success',
        name: pluginName,
        message: `插件 ${pluginName} 载入成功`,
      });
      return { name: pluginName, module: module };
    },
    (error) => {
      const pluginName = file.replace('.js', '');
      pluginLogs.push({
        type: 'error',
        name: pluginName,
        message: `载入插件 ${pluginName} 失败：${logger.red(pluginName)}`,
        error: error,
      });
      return { name: pluginName, error: error };
    }
  ));
});

// 等待所有插件加载完成
let apps = {};
ret = await Promise.allSettled(ret);

ret.forEach((result, index) => {
  const pluginName = files[index].replace('.js', '');

  if (result.status === 'fulfilled' && !result.value.error) {
    apps[pluginName] = result.value.module[Object.keys(result.value.module)[0]];
  }
});

// 打印插件加载总结
let pluginSummary = '';
let successCount = 0;
let failureCount = 0;

pluginLogs.forEach((log) => {
  if (log.type === 'success') {
    successCount++;
    pluginSummary += `${log.message}\n`;
  } else if (log.type === 'error') {
    failureCount++;
    pluginSummary += `${log.message}\n错误详情：${log.error.message}\n`;
  }
});

// 统一输出最终日志
const endMessage = `
\x1b[38;2;255;105;180m
------------------------------------------------
${pluginSummary}
------------------------------------------------
| 皮皮ちゃん的插件加载完成！                   |
|  成功加载: ${successCount} 个插件            |
|  失败加载: ${failureCount} 个插件            |
|  总共尝试加载: ${files.length} 个插件        |
----------------------------------------------------
\x1b[0m
`;
logger.info(endMessage);

export { apps };